﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using LDSP.BRL;
using System.Net.Mail;
using BLL.Util;
using LDSP.Util;
using LDSP.Helper;
using BYFW.WebBase;

namespace LDSP.UI
{
    /// <summary>
    /// 本页面跳过验证码，便于自动登录。
    /// 只能是指定的客户指定的IP登陆。
    /// </summary>
    public partial class AutoLogin : BRL.BasePage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            bool fobidAutoLogin = Request.QueryString["FOBID_AUTO_LOGIN"] == "true";
            if (!fobidAutoLogin)
            {
                this.Session.Add(SessionKeys.AutoLogin, "AUTO_U_LOGIN");//保留此逻辑，用于跳过验证码登陆
            }
        }

        public override void RedirectBefore()
        {
            //Note：本页面不需要进行页面跳转判断
        }

        protected void btn_ok_Click(object sender, EventArgs e)
        {
            try
            {
                LoginWithCookie(this.txt_name.Text.Trim(), this.txt_pwd.Text, "", this.chkRememberMe.Checked);
            }
            catch (Exception ex)
            {
                this.HandlerException(ex);
            }
        }

        private void LoginWithCookie(string userName, string password, string validateCode, bool needWriteCookie)
        {
            if (new AutoLoginAuthentication().CheckPermission(userName, this.GetUserIP()))
            {
                if (this.Login(userName, password, validateCode, 1))
                {
                    //写cookie.
                    if (needWriteCookie)
                    {
                        new LDSPCookie().WriteCookie(Response, CookieKeys.UserName, this.txt_name.Text.Trim());
                        new LDSPCookie().WriteCookie(Response, CookieKeys.Password, this.txt_pwd.Text);
                    }

                    //页面跳转.
                    string redirectUrl = string.Empty;
                    if (LoginUser != null)
                    {
                        if (LoginUser.UserType == EnterpriseUserType.企业管理员)
                        {
                            redirectUrl = "~/UI/EnterpriseAdmin/Index.aspx";
                        }
                        else
                        {
                            redirectUrl = "~/UI/EnterpriseCommonUser/Index.aspx";
                        }

                        this.Response.Redirect(redirectUrl);
                    }
                }
            }
            else
            {
                this.JSAlert("您提供的用户名不允许在此页面登陆，请转到登陆页面:" + HttpContext.Current.Request.Url.Host);
            }

            this.Session.Remove(SessionKeys.AutoLogin);
        }
    }
}